<template>
  <div class="change-page">
    <el-container style="height: 100vh; border: 1px solid #eee">
      <el-main class="main-content">
        <!-- 头部区域 -->
        <div class="header-container">
          <el-button @click="goBack" class="back-button" size="mini">
            <i class="el-icon-arrow-left"></i> 返回
          </el-button>
          <h2 class="page-title">{{ pageTitle }}</h2>
        </div>

        <!-- 主内容卡片 -->
        <el-card class="change-card">
          <el-form :model="formData" ref="changeForm" label-width="120px" class="change-form" :rules="formRules">
            <!-- 手机号码修改表单 -->
            <template v-if="type === 'phone'">
              <el-form-item label="当前手机号码" disabled>
                <el-input v-model="formData.oldPhone" placeholder="请输入原手机号"></el-input>
              </el-form-item>

              <el-form-item label="新手机号码" prop="newPhone">
                <el-input v-model="formData.newPhone" placeholder="请输入新手机号码" maxlength="11"
                  @input="formatPhone"></el-input>
              </el-form-item>

              <el-form-item label="当前密码" prop="oldPassword">
                <el-input v-model="formData.oldPassword" type="password" placeholder="请输入密码" show-password></el-input>
              </el-form-item>

            </template>

            <!-- 密码修改表单 -->
            <template v-if="type === 'password'">
              <el-form-item label="当前手机号码" disabled>
                <el-input v-model="formData.oldPhone" placeholder="请输入原手机号"></el-input>
              </el-form-item>
              <el-form-item label="当前密码" prop="oldPassword">
                <el-input v-model="formData.oldPassword" type="password" placeholder="请输入当前密码" show-password></el-input>
              </el-form-item>

              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="formData.newPassword" type="password" placeholder="请输入新密码（4-20位，包含字母和数字）"
                  show-password @input="checkPasswordStrength"></el-input>
                <!-- 密码强度提示 -->
                <div class="password-strength" v-if="formData.newPassword">
                  <div class="strength-label">密码强度：</div>
                  <div class="strength-bars">
                    <div class="strength-bar" :class="strengthClass[0]"></div>
                    <div class="strength-bar" :class="strengthClass[1]"></div>
                    <div class="strength-bar" :class="strengthClass[2]"></div>
                  </div>
                  <div class="strength-text">{{ strengthText }}</div>
                </div>
              </el-form-item>

              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input v-model="formData.confirmPassword" type="password" placeholder="请再次输入新密码"
                  show-password></el-input>
              </el-form-item>
            </template>

            <!-- 操作按钮 -->
            <el-form-item class="form-actions">
              <el-button type="primary" @click="submitForm">确认修改</el-button>
              <el-button @click="goBack">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { resetPhone,resetPassword } from '@/api/manager/manage';
import webSocketService from '@/util/manager_api/websocket-serve';
export default {
  data() {
    // 密码强度校验规则
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入新密码'));
      } else if (value.length < 4 || value.length > 20) {
        callback(new Error('密码长度必须在4-20位之间'));
      } else if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]+$/.test(value)) {
        callback(new Error('密码必须包含字母和数字'));
      } else {
        callback();
      }
    };

    // 确认密码校验
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请确认新密码'));
      } else if (value !== this.formData.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };

    return {
      // 页面类型（phone/password）
      type: '',
      // 表单数据
      formData: {
        oldPhone:'',
        newPhone: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 当前手机号
      currentPhone: '',
      countdown: 60,
      // 密码强度相关
      strengthClass: ['', '', ''],
      strengthText: '',
      // 表单验证规则
      formRules: {
        newPhone: [
          { required: true, message: '请输入新手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        oldPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        newPassword: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    ...mapGetters('manager', ['userInfo']),
    // 页面标题
    pageTitle() {
      return this.type === 'phone' ? '修改手机号码' : '修改密码';
    }
  },
  created() {
    // 从路由参数获取类型
    this.type = this.$route.query.type || '';
    if (!['phone', 'password'].includes(this.type)) {
      this.$message.error('参数错误');
      this.goBack();
      return;
    }
    // 初始化当前手机号
    this.currentPhone = this.userInfo.phone || '未设置';
  },
  methods: {
    // 格式化手机号输入
    formatPhone() {
      this.formData.newPhone = this.formData.newPhone.replace(/[^\d]/g, '');
    },

    // 检查密码强度
    checkPasswordStrength() {
      const password = this.formData.newPassword;
      if (!password) return;

      let strength = 0;
      // 包含小写字母或大写字母
      if (/[a-zA-Z]/.test(password)) strength++;
      // 包含数字
      if (/[0-9]/.test(password)) strength++;
      // 长度超过10位或包含特殊字符
      if (password.length > 10 || /[^a-zA-Z0-9]/.test(password)) strength++;

      // 设置强度样式和文本
      this.strengthClass = ['', '', ''];
      for (let i = 0; i < strength; i++) {
        this.strengthClass[i] = 'active-' + (i + 1);
      }

      const strengthTexts = ['弱', '中', '强'];
      this.strengthText = strengthTexts[strength - 1] || '';
    },

    // 提交表单
    async submitForm() {
      this.$refs.changeForm.validate(async (valid) => {
        if (!valid) return;
        try {
          let response;
          if (this.type === 'phone') {
            // 修改手机号
            response = await resetPhone({
              oldPhone: this.formData.oldPhone,
              newPhone: this.formData.newPhone,
              password: this.formData.oldPassword
            });
          } else {
            // 修改密码
            response = await resetPassword({
              phone: this.formData.oldPhone,
              oldPassword: this.formData.oldPassword,
              newPassword: this.formData.newPassword
            });
          }

          if (response.data.code === 201) {
            // 更新Vuex中的用户信息（如果是手机号）
            if (this.type === 'phone') {
              this.$store.commit('manager/SET_USER_INFO', {
                ...this.userInfo,
                phone: this.formData.newPhone
              });
            }
            // 延迟跳转，让用户看到成功提示
            setTimeout(() => {
              this.$store.commit('manager/CLEAR_STATE');
              this.$message({
                type:'success',
                message:'修改成功，请重新登录'
              })
              webSocketService.close();
              this.$router.push('manage-login');
            },1500);
          } else {
            this.$message.error(response.data.message || '修改失败');
          }
        } catch (error) {
          console.error('修改失败:', error);
          this.$message.error('网络错误，请稍后重试');
        }
      });
    },

    // 返回上一页
    goBack() {
      this.$router.back();
    }
  }
};
</script>


<style scoped>
/* 主内容区样式 */
.main-content {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 头部样式 */
.header-container {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eaecef;
}

.page-title {
  margin: 0;
  font-size: 20px;
  color: #1f2d3d;
  font-weight: 600;
}

.back-button {
  margin-right: 16px;
  transition: all 0.2s;
}

.back-button:hover {
  transform: translateX(-3px);
}

/* 卡片样式 */
.change-card {
  max-width: 600px;
  margin: 0 auto;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  border: none;
  overflow: hidden;
}

/* 表单样式 */
.change-form {
  padding: 30px;
}

/* 密码强度样式 */
.password-strength {
  display: flex;
  align-items: center;
  margin-top: 8px;
  font-size: 12px;
}

.strength-label {
  color: #606266;
  margin-right: 8px;
}

.strength-bars {
  display: flex;
  gap: 4px;
  flex: 1;
}

.strength-bar {
  height: 6px;
  flex: 1;
  background-color: #e5e6eb;
  border-radius: 3px;
  transition: all 0.3s;
}

/* 强度等级样式 */
.active-1 {
  background-color: #ff4d4f;
}

.active-2 {
  background-color: #faad14;
}

.active-3 {
  background-color: #52c41a;
}

.strength-text {
  color: #606266;
  margin-left: 8px;
  min-width: 40px;
}

/* 按钮区域样式 */
.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px dashed #e5e6eb;
}

.form-actions button {
  min-width: 120px;
  height: 40px;
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 16px;
  }

  .change-card {
    max-width: 100%;
  }

  .change-form {
    padding: 20px;
  }

  .el-form-item__label {
    text-align: left;
    padding: 0 0 8px 0;
  }
}
</style>